package com.tbgov.controller;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.google.gson.Gson;
import com.tbgov.service.RedisTokenService;
import darabonba.core.client.ClientOverrideConfiguration;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * @author 1st
 */
@Slf4j
@Tag(name = "短信服务", description = "短信相关接口")
@RestController
@RequestMapping("/sms")
public class SmsController {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RedisTokenService redisTokenService;

    private final AsyncClient client;

    public SmsController() {
        // 配置阿里云 SDK
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId("LTAI5tF9rDzFteNtNinNiYQq")
                .accessKeySecret("yCnVNKABbgfxnPvjGIZpNqxKflx0vb")
                .build());

        this.client = AsyncClient.builder()
                .region("cn-hangzhou") // 地域
                .credentialsProvider(provider)
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride("dysmsapi.aliyuncs.com")
                )
                .build();
    }

    @Operation(summary = "发送短信验证码")
    @GetMapping ("/send")
    ResponseEntity<Object> sendSms(@Parameter(name = "phoneNumber", description = "手机号码", required = true) @RequestParam String phoneNumber) {
        // 生成随机验证码
        String code = generateVerificationCode();

        // 配置请求参数
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .signName("天宝服务") // 替换为你的签名
                .templateCode("SMS_307645131") // 替换为你的模板代码
                .phoneNumbers(phoneNumber)
                .templateParam("{\"code\":\"" + code + "\"}")
                .build();

        // 异步发送短信
        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);

        response.thenAccept(resp -> {
            String result = new Gson().toJson(resp);
            System.out.println("短信发送成功: " + result);
            if ("OK".equals(resp.getBody().getCode())) {
                // 成功发送后将验证码存入 Redis
                redisTemplate.opsForValue().set(redisTokenService.getRedisKey(phoneNumber), code, 5, TimeUnit.MINUTES);
            } else {
                log.info("短信发送失败: {}", resp.getBody());
                throw new IllegalArgumentException("短信发送失败: " + resp.getBody().getMessage());
            }
        }).exceptionally(throwable -> {
            log.info("短信发送异常: {}", throwable.getMessage());
            throw new IllegalArgumentException("短信发送异常: " + throwable.getMessage());
        });
        return ResponseEntity.ok("success");
    }

    @GetMapping("/verify")
    ResponseEntity<Object> verifyCode(@RequestParam String phoneNumber, @RequestParam String code) {
        redisTokenService.verifyCode(phoneNumber, code);
        return ResponseEntity.ok("success");
    }

    // 工具方法：生成随机6位验证码
    private String generateVerificationCode() {
        Random random = new Random();
        return String.format("%06d", random.nextInt(1000000)); // 生成6位随机数字
    }

}
